package org.hospital.controller;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpSession;

import org.hospital.entity.Bill;
import org.hospital.entity.BillProject;
import org.hospital.entity.BillProjectId;
import org.hospital.entity.Employee;
import org.hospital.entity.Log;
import org.hospital.entity.MedicalCard;
import org.hospital.entity.Project;
import org.hospital.service.BillProjectService;
import org.hospital.service.BillService;
import org.hospital.service.LogService;
import org.hospital.service.MedicalCardService;
import org.hospital.service.PermissionService;
import org.hospital.service.ProjectService;
import org.hospital.service.UserService;
import org.hospital.util.Constant;
import org.hospital.util.DateUtil;
import org.hospital.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.context.request.WebRequest;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

@Controller
@RequestMapping("billController")
@SessionAttributes(value = "employee", types = Employee.class)
public class BillController {

	@Autowired
	private PermissionService pmService;
	@Autowired
	private ProjectService pjService;
	@Autowired
	private BillService bService;
	@Autowired
	private BillProjectService bpService;
	@Autowired
	private MedicalCardService mcService;
	@Autowired
	private UserService uService;
	@Autowired
	private LogService lService;

	/**
	 * 添加治疗项目单据 参数格式 { clientId:xx,doctorId:xx, status:xx, sum,
	 * projcets:[{projectId:xx,number:xx,deadline:xx,extraInfo:xx}]}
	 * 
	 * @param req
	 * @param session
	 * @return 402：权限不足；405：session不存在，重新登陆；200：操作成功
	 */
	//TODO 没有做事务控制
	@ResponseBody
	@RequestMapping(value = "/addTreatmentBill", produces = "text/json;charset=utf-8")
	public String addTreatmentBill(WebRequest req, HttpSession session) {
		// 检测用户权限
		Employee operator = (Employee) session.getAttribute("employee");
		if (operator == null) {
			return StringUtil.setResult(405, "请重新登录", "");
		}
		if (!pmService.isPermisionEnough(operator.getPositionId(),
				Constant.CREATE_TREATMENT_BILL.getName(), 1)) {
			return StringUtil.setResult(402, "权限不足", "");
		}

		try {
			int clientId = Integer.parseInt(req.getParameter("clientId"), 10);
			int doctorId = Integer.parseInt(req.getParameter("doctorId"), 10);
			int status = Integer.parseInt(req.getParameter("status"), 10);
			JSONArray projects = JSONArray.parseArray(req.getParameter("projects"));
			Double totalPrice = Double.parseDouble(req.getParameter("sum"));
			long dateTimeLong = DateUtil.getShortDateLong(req.getParameter("submitTime"));
			String diseaseName = req.getParameter("diseaseName");
			
			if(dateTimeLong == -1) {
				return StringUtil.setResult(403, "参数有误", "");
			}
			
			//System.out.println("addTreatmentBill projects : " + JSON.toJSONString(projects, false));
			Employee doctor = uService.getEmployeeById(doctorId);
			// 插入bill表数据
			Bill bill = new Bill();
			bill.setClientId(clientId);
			bill.setOperatorId(operator.getEmployeeId());
			bill.setDoctorId(doctorId);
			bill.setDepartmentId(doctor.getDepartmentId());
			bill.setClinicId(doctor.getClinicId());
			bill.setCategory(Constant.TREATMENT_BILL.getName());
			bill.setTotalPrice(totalPrice);
			bill.setTotalCost(0.0);
			bill.setDatetime(new Timestamp(dateTimeLong));
			bill.setStatus(status);

			//System.out.println("addTreatmentBill bill 插入数据库前: " + JSON.toJSONString(bill));
			bill = bService.addTreatBill(bill, projects, clientId, dateTimeLong,diseaseName);
			//System.out.println("addTreatmentBill bill 插入数据库后: " + bill.getBillId());

			// 记录日志
			Log log = new Log();
			log.setEmployeeId(operator.getEmployeeId());
			log.setOperate(Constant.CREATE_TREATMENT_BILL.getName());
			log.setOperateTime(new Timestamp(DateUtil.getNowLong()));
			log.setContent(JSON.toJSONString(bill));
			lService.addEntity(log);

			return StringUtil.setResult(200, "添加成功", "");
		} catch (Exception e) {
			e.printStackTrace();
			return StringUtil.setResult(403, "参数有误", "");
		}
		// 获取数据
		
	}

	/**
	 * 添加费用单据 参数格式 
	 * { clientId:xxx, clinicId:xxx, departmentId:xxx, status:xxx,
	 * sum:xxx, 利润 incomeSum:xxx, 收入 paySum:xxx, 支出 submitTime:xxx, 单据所属时间
	 * projects:[{markText:xxx(摘要),projectId:xxx,costType:xxx,price:xxx}], }
	 * 
	 * @param req
	 * @param session
	 * @return 402：权限不足；405：session不存在，重新登陆；200：操作成功
	 */
	@ResponseBody
	@RequestMapping(value = "/addFundBill", produces = "text/json;charset=utf-8")
	public String addFundBill(WebRequest req, HttpSession session) {
		// 检测用户权限
		Employee operator = (Employee) session.getAttribute("employee");
		if (operator == null) {
			return StringUtil.setResult(405, "请重新登录", "");
		}
		if (!pmService.isPermisionEnough(operator.getPositionId(), Constant.CREATE_FUND_BILL.getName(), 1)) {
			return StringUtil.setResult(402, "权限不足", "");
		}

		// 获取数据
		try {
			int clientId = Integer.parseInt(req.getParameter("clientId"), 10);
			int clnicId = Integer.parseInt(req.getParameter("clinicId"), 10);
			int departmentId = Integer.parseInt(req.getParameter("departmentId"), 10);
			int status = Integer.parseInt(req.getParameter("status"), 10);
			double totalCost = Double.parseDouble(req.getParameter("paySum"));
			double totalPrice = Double.parseDouble(req.getParameter("incomeSum"));
			Timestamp datetime = new Timestamp(
					DateUtil.getShortDateLong(req.getParameter("submitTime")));
			JSONArray projects = JSONArray.parseArray(req.getParameter("projects"));

			// 插入bill表
			Bill bill = new Bill();
			bill.setClientId(clientId);
			bill.setOperatorId(operator.getEmployeeId());
			bill.setDoctorId(0);
			bill.setClinicId(clnicId);
			bill.setDepartmentId(departmentId);
			bill.setCategory(Constant.FUND_BILL.getName());
			bill.setTotalCost(totalCost);
			bill.setTotalPrice(totalPrice);
			bill.setDatetime(datetime);
			bill.setStatus(status);

			//System.out.println("addTreatmentBill bill 插入数据库前: " + JSON.toJSONString(bill));
			bill = bService.addFundBill(bill, projects);
			//System.out.println("addTreatmentBill bill 插入数据库后: " + JSON.toJSONString(bill));

			// 记录日志
			Log log = new Log();
			log.setEmployeeId(operator.getEmployeeId());
			log.setOperate(Constant.CREATE_FUND_BILL.getName());
			log.setOperateTime(new Timestamp(DateUtil.getNowLong()));
			log.setContent(JSON.toJSONString(bill));
			lService.addEntity(log);

			return StringUtil.setResult(200, "添加成功", "");
		} catch (Exception e) {
			e.printStackTrace();
			return StringUtil.setResult(403, "参数有误", "");
		}
	}
	
	/**
	 * 查看单据表
	 * 参数格式{date1:xxx,date2:xxx,category:xxx}
	 */
	@ResponseBody
	@RequestMapping(value = "/checkBill", produces = "text/json;charset=utf-8")
	public String checkBill(WebRequest req, HttpSession session){
		Employee operator = (Employee) session.getAttribute("employee");
		if (operator == null) {
			return StringUtil.setResult(405, "请重新登录", "");
		}
		try{
			Timestamp date1 = new Timestamp(DateUtil.getShortDateLong(req.getParameter("date1")));
			Timestamp date2 = new Timestamp(DateUtil.getShortDateLong(req.getParameter("date2")));
			String category = req.getParameter("category");
			JSONArray ja = bService.getBill(date1, date2, category);
			if(ja == null || ja.size() == 0){
				return StringUtil.setResult(414, "数据为空", "");
			}
			return StringUtil.setResult(200, "操作成功", ja);
		}catch(Exception e){
			e.printStackTrace();
			return StringUtil.setResult(403, "参数格式有误", "");
		}
	}
	
	/**
	 * 查看单据详情表
	 * 参数格式{billId}
	 */
	@ResponseBody
	@RequestMapping(value = "/checkBillDetail", produces = "text/json;charset=utf-8")
	public String getBillDetail(WebRequest req,HttpSession session){
		Employee operator = (Employee) session.getAttribute("employee");
		if (operator == null) {
			return StringUtil.setResult(405, "请重新登录", "");
		}
		try{
			int billId = Integer.parseInt(req.getParameter("billId"));
			JSONArray ja = bpService.getBillDetailTable(billId);
			if(ja == null || ja.size() == 0){
				return StringUtil.setResult(414, "数据为空", "");
			}
			return StringUtil.setResult(200, "操作成功", ja);
		}catch(Exception e){
			e.printStackTrace();
			return StringUtil.setResult(403, "参数格式有误", "");
		}
	}
}
